package com.aplink.generic.handler;

import android.os.Handler;
import android.os.Message;

import com.aplink.generic.GenericFragment;
import com.aplink.generic.constant.type.ActionType;
import com.aplink.generic.webservice.GenericWebService;

public class WebserviceHandler extends Handler {
	private final GenericFragment mGenericFragment;

	public WebserviceHandler(final GenericFragment genericFragment) {
		this.mGenericFragment = genericFragment;
	}

	@Override
	public void handleMessage(final Message msg) {
		final ActionType actionType = ActionType.get(msg.what);
		if (actionType.equals(ActionType.LOGIN)) {
			GenericWebService.newInstance(this.mGenericFragment).login()
			        .excute();
		} else if (actionType.equals(ActionType.INIT_DATA)) {
			GenericWebService.newInstance(this.mGenericFragment)
			        .initializeData().excute();
		} else if (actionType.equals(ActionType.DOWNLOAD_ALL)) {
			GenericWebService.newInstance(this.mGenericFragment).downloadAll()
			        .excute();
		} else if (actionType.equals(ActionType.DOWNLOAD)) {
			GenericWebService.newInstance(this.mGenericFragment).download()
			        .excute();
		} else if (actionType.equals(ActionType.UPLOAD)) {
			GenericWebService.newInstance(this.mGenericFragment).upload()
			        .excute();
		} else if (actionType.equals(ActionType.INSERT)) {
			GenericWebService.newInstance(this.mGenericFragment).insert()
			        .excute();
		} else if (actionType.equals(ActionType.UPDATE)) {
			GenericWebService.newInstance(this.mGenericFragment).update()
			        .excute();
		} else if (actionType.equals(ActionType.DELETE)) {
			GenericWebService.newInstance(this.mGenericFragment).delete()
			        .excute();
		} else if (actionType.equals(ActionType.SAVE)) {
			GenericWebService.newInstance(this.mGenericFragment).save()
			        .excute();
		} else if (actionType.equals(ActionType.FORGOT_PASSWORD)) {
			GenericWebService.newInstance(this.mGenericFragment)
			        .forgotPassword().excute();
		}
	}

	public void sendAction(final ActionType actionType) {
		sendEmptyMessage(actionType.getCode());
	}

	public void sendMessage(final ActionType actionType, final Object object) {
		final Message message = Message.obtain(this, actionType.getCode(),
		        object);
		message.sendToTarget();
	}
}
